﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace CPPEI.Coolzon.Common
{
    public class Serializer
    {

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static XElement XmlSerializer<T>(T obj)
        {
            try
            {
                XElement res = null;
                XmlSerializer ser = new XmlSerializer(obj.GetType());
                Stream stream = new MemoryStream();
                ser.Serialize(stream, obj);
                stream.Seek(0, SeekOrigin.Begin);
                using (StreamReader reader = new StreamReader(stream))
                {
                    res = XElement.Load(reader);
                }
                stream.Close();
                return res;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        public static T XmlDeserialize<T>(string serializeString)
        {
            try
            {
                XElement xe = null;
                XmlSerializer ser = new XmlSerializer(typeof(T));
                Stream stream = new MemoryStream();
                byte[] bytes = System.Text.Encoding.Default.GetBytes(serializeString);
                stream.Write(bytes, 0, bytes.Length);
                stream.Seek(0, SeekOrigin.Begin);
                using (StreamReader reader = new StreamReader(stream))
                {
                    xe = XElement.Load(reader);
                }
                return (T)ser.Deserialize(xe.CreateReader());
            }
            catch
            {
                return default(T);
            }
        }
    }
}
